package com.settlement.system.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.common.annotation.PreventDuplicateSubmit;
import com.settlement.system.common.constant.KafkaConstants;
import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.common.enums.PlatFormEnum;
import com.settlement.system.common.model.Option;
import com.settlement.system.common.result.PageResult;
import com.settlement.system.common.result.Result;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.common.util.EasyExcelImportUtils;
import com.settlement.system.common.util.RequestUtils;
import com.settlement.system.common.util.StringUtils;
import com.settlement.system.listener.easyexcel.TmFundFlowListener;
import com.settlement.system.model.entity.KafkaSendErrorRecord;
import com.settlement.system.model.entity.SysBaseColumnMatch;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.entity.TmFundFlow;
import com.settlement.system.model.form.TmFundFlowForm;
import com.settlement.system.model.query.TmFundFlowQuery;
import com.settlement.system.model.vo.PddDepositImportVo;
import com.settlement.system.model.vo.TmFundFlowImportVo;
import com.settlement.system.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * <p>
 * 天猫资金流水 前端控制器
 * </p>
 *
 * @author huangrensen
 * @since 2024-04-25
 */
@RestController
@RequestMapping("/api/v1/tmFundFlow")
@RequiredArgsConstructor
public class TmFundFlowController {

    private final Logger logger = LoggerFactory.getLogger(TmFundFlowController.class);

    @Value("${system.config.secret}")
    private String secret;

    @Value("${system.config.appId}")
    private String appId;

    private final TmFundFlowService tmFundFlowService;

    private final SysBaseColumnMatchService baseColumnMatchService;

    private final PlatformSourceDataService platformSourceDataService;

    private final SysDictService dictService;

    private final KafkaTemplate<String, String> kafkaTemplate;

    private final SysStoreService storeService;

    private final SysLogRecordService logRecordService;

    private final KafkaSendErrorRecordService kafkaSendErrorRecordService;
    private final SnowflakeIdWorker snowflakeIdWorker = SnowflakeIdWorker.getInstance();

    @GetMapping("/page")
    public PageResult<TmFundFlow> getPage(@ParameterObject TmFundFlowQuery queryParams) {
        Page<TmFundFlow> result = tmFundFlowService.getPage(queryParams);
        return PageResult.success(result);
    }


    @Operation(summary = "保存天猫资金流水", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping
    @PreventDuplicateSubmit
    @PreAuthorize("@ss.hasPerm('sys:tmFundFlow:save')")
    public Result<?> saveTmFundFlow(@RequestBody @Valid TmFundFlowForm tmFundFlowForm) {
        boolean result = tmFundFlowService.saveTmFundFlow(tmFundFlowForm);
        return Result.judge(result);
    }

    @Operation(summary = "获取天猫资金流水信息", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/{id}/form")
    public Result<TmFundFlowForm> getTmFundFlowFormData(@Parameter(description = "主键ID") @PathVariable Long id) {
        TmFundFlowForm tmFundFlow = tmFundFlowService.getTmFundFlowFormData(id);
        return Result.success(tmFundFlow);
    }

    @Operation(summary = "删除天猫资金流水", security = {@SecurityRequirement(name = "Authorization")})
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('sys:tmFundFlow:delete')")
    public Result<?> deleteTmFundFlow(@Parameter(description = "ID，多个以英文逗号(,)分割") @PathVariable String ids) {
        boolean result = tmFundFlowService.deleteTmFundFlow(ids);
        return Result.judge(result);
    }

    @Operation(summary = "天猫资金流水导入", security = {@SecurityRequirement(name = "Authorization")})
    @PostMapping("/tmFundFlowImport/{storeCode}")
    @PreAuthorize("@ss.hasPerm('sys:tmFundFlow:import')")
    @PreventDuplicateSubmit
    public Result<?> tmFundFlowImport(@RequestParam("file") MultipartFile file, @PathVariable String storeCode) throws Exception {
        this.uploadFile(file, storeCode);
        return Result.success();
    }

    @Operation(summary = "天猫资金流水RPA导入")
    @PostMapping("/tmFundFlowRPAImport/{storeCode}")
    @PreventDuplicateSubmit
    public Result<?> tmFundFlowRPAImport(HttpServletRequest request, @RequestParam("file") MultipartFile file, @PathVariable String storeCode, @RequestParam("orderType") String orderType, @RequestParam("period") String period) throws Exception {
        Result<?> result = RequestUtils.resolveAppToken(request, secret, appId);
        if (!Result.isSuccess(result)) {
            return result;
        }
        boolean canRun = logRecordService.checkCanRun(storeCode, orderType, period);
        if (canRun) {
            this.uploadFile(file, storeCode);
        }
        return Result.success();
    }

    private void uploadFile(MultipartFile file, @PathVariable String storeCode) throws Exception {
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        ExcelTypeEnum excelTypeEnum = null;
        if ("xls".equalsIgnoreCase(fileType)) {
            excelTypeEnum = ExcelTypeEnum.XLS;
        } else if ("xlsx".equalsIgnoreCase(fileType)) {
            excelTypeEnum = ExcelTypeEnum.XLSX;
        } else if ("csv".equalsIgnoreCase(fileType)) {
            excelTypeEnum = ExcelTypeEnum.CSV;
        }
        Assert.isTrue(Objects.nonNull(excelTypeEnum), "不支持的文件类型");
        SysStore sysStore = storeService.getByCode(storeCode);
        List<Map<String, String>> mapList = EasyExcelImportUtils.makeData(file, null, 0, 5, Charset.forName("GBK"));
        if (mapList.size() == 0) {
            return;
        }
        Set<String> stringSet = mapList.get(0).keySet();
        String billTypeKey = "tmFundFlow";
        List<Option> optionList = dictService.listDictOptions(billTypeKey);
        Map<String, String> keyMap = new HashMap<>();
        for (Option option : optionList) {
            if(StringUtils.hasText(option.getRemark())){
                continue;
            }
            // 数据库字段 转换成 java字段 （下划线转驼峰）
            keyMap.put(option.getLabel(), StringUtils.lineToHump(option.getValue().toString()));
        }
        Map<String, String> resultMap = platformSourceDataService.checkImportFileTitle(stringSet, keyMap);
        if (resultMap.size() > 0) {
            // 发送企业微信通知
            List<Option> platformOptionList = dictService.listDictOptions(SystemConstants.PLATFORM_KEY);
            List<String> messageList = new ArrayList<>();
            resultMap.forEach((key, value) -> messageList.add("【%s】：【%s】".formatted(key, value)));
            Option option = platformOptionList.stream().filter(item -> Objects.equals(item.getValue(), sysStore.getStoreKey())).findFirst().orElse(null);
            platformSourceDataService.sendMessage(option.getLabel(), sysStore.getCommercePlatformStoreName(), "天猫资金流水", String.join("\n", messageList), file);
            return;
        }
        List<TmFundFlowImportVo> list = new ArrayList<>();
        String columnEn;
        TmFundFlowImportVo importVo;
        Set<String> columnSet;
        Map<String, String> dataMap;
        for (Map<String, String> stringStringMap : mapList) {
            columnSet = stringStringMap.keySet();
            dataMap = new HashMap<>();
            for (String columnCn : columnSet) {
                columnEn = keyMap.get(columnCn.replaceAll("\uFEFF", ""));
                dataMap.put(columnEn, stringStringMap.get(columnCn));
            }
            importVo = new TmFundFlowImportVo();
            BeanUtils.populate(importVo, dataMap);
            list.add(importVo);
        }
        // 过滤发生时间为空的数据
        list.removeIf(item -> Objects.isNull(item.getOrderTime()));
        // 通过配置获取账单月份【billMonth】
        String billType = "天猫资金流水";
        List<SysBaseColumnMatch> configListByPlatform = baseColumnMatchService.getBusinessConfigListByPlatform(PlatFormEnum.TMALL_CONFIG.getValue());
        configListByPlatform = configListByPlatform.stream().filter(item -> item.getBillType().equals(billType)).toList();
        List<SysBaseColumnMatch> configListByPlatformFilter;
        // 先找业务日期
        configListByPlatformFilter = configListByPlatform.stream().filter(item -> Objects.equals(item.getStandardColumn(), SystemConstants.BUSINESS_DATE)).toList();
        if (configListByPlatformFilter.size() == 0) {
            // 再查找出账日期
            configListByPlatformFilter = configListByPlatform.stream().filter(item -> Objects.equals(item.getStandardColumn(), SystemConstants.OUT_BILL_DATE)).toList();
        }
        Assert.notEmpty(configListByPlatformFilter, "【%s】没有配置【业务日期或出账日期】，导入失败".formatted(billType));
        String sourceColumn = configListByPlatformFilter.get(0).getSourceColumn();
        String sourceColumnEn = TmFundFlowImportVo.getKeyMap().get(sourceColumn);
        String billMonth;
        Object object;
        for (TmFundFlowImportVo fundFlowImportVo : list) {
            fundFlowImportVo.setStoreId(sysStore.getId());
            // 通过反射获取字段值
            Field declaredField = fundFlowImportVo.getClass().getDeclaredField(sourceColumnEn);
            declaredField.setAccessible(true);
            object = declaredField.get(fundFlowImportVo);
            // 检查数据是否正确
            Assert.notNull(object, "【%s】配置的【业务日期或出账日期】对应的原始账单【%s】有空值，导入失败".formatted(billType, sourceColumn));
            if ("null".equalsIgnoreCase(object.toString().strip())) {
                object = null;
            }
            Assert.notNull(object, "【%s】配置的【业务日期或出账日期】对应的原始账单【%s】有空值，导入失败".formatted(billType, sourceColumn));
            String sourceColumnValue = object.toString();
            billMonth = DateUtils.formatDate(DateUtils.convertStringToLocalDateTime(sourceColumnValue));
            Assert.notNull(billMonth, "【%s】配置的【业务日期或出账日期】对应的原始账单【%s】的值【%s】转换成业务日期失败，导入失败".formatted(billType, sourceColumn, sourceColumnValue));
            fundFlowImportVo.setBillMonth(billMonth);
        }
        for (TmFundFlowImportVo fundFlowImportVo : list) {
            // 为了避免消息重复消费，生成一个消息ID
            fundFlowImportVo.setUuid(snowflakeIdWorker.nextId());
            CompletableFuture<SendResult<String, String>> completableFuture = kafkaTemplate.send(KafkaConstants.HWG_TOPIC_TM_FUND_FLOW, JSONObject.toJSONString(fundFlowImportVo));
            completableFuture.whenComplete((result, throwable) -> {
                if(Objects.nonNull(throwable)){
                    throwable.printStackTrace();
                    logger.error("消息发送失败，消息ID：{}，原因：{}", fundFlowImportVo.getUuid(), throwable.getMessage());
                    KafkaSendErrorRecord errorRecord = new KafkaSendErrorRecord();
                    errorRecord.setDataText(JSONObject.toJSONString(fundFlowImportVo));
                    errorRecord.setQueueName(KafkaConstants.HWG_TOPIC_TM_FUND_FLOW);
                    errorRecord.setRemark(throwable.getMessage());
                    errorRecord.setUuid(fundFlowImportVo.getUuid());
                    kafkaSendErrorRecordService.checkAndSave(errorRecord);
                }
            });
        }
    }

    @Operation(summary = "导出天猫资金流水", security = {@SecurityRequirement(name = "Authorization")})
    @GetMapping("/_export")
    @PreAuthorize("@ss.hasPerm('sys:tmFundFlow:export')")
    @PreventDuplicateSubmit
    public void export(@RequestParam("ids") String ids, HttpServletResponse response) throws IOException {
        String fileName = "天猫资金流水.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));

        List<TmFundFlowImportVo> tmFundFlowList = tmFundFlowService.findByIds(ids);
        EasyExcel.write(response.getOutputStream(), TmFundFlowImportVo.class).sheet("天猫资金流水").doWrite(tmFundFlowList);
    }
}

